<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form ref="loginForm" @submit="login">
      <van-field
        placeholder="请输入手机号"
        v-model.trim="user.mobile"
        :rules="formRules.mobile"
        name="mobile"
      >
        <i class="toutiao toutiao-shouji" slot="left-icon"></i>
      </van-field>
      <van-field
        placeholder="请输入验证码"
        v-model="user.code"
        :rules="formRules.code"
      >
        <i class="toutiao toutiao-yanzhengma" slot="left-icon"></i>
        <template #button>
          <van-count-down
            @finish="sending = false"
            v-if="sending"
            :time="time"
            format="ss 秒"
          >
          </van-count-down>
          <van-button
            v-else
            size="small"
            round
            type="default"
            @click="sendCode"
            native-type="button"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div class="login-btn">
        <van-button block type="info" native-type="submit" :loading="loading"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { sendSms, login } from "@/api/user";
export default {
  name: "Login",
  data() {
    return {
      time: 60000,
      sending: false,
      loading: false,
      user: {
        mobile: "",
        code: "",
      },
      formRules: {
        mobile: [
          { required: true, message: "手机号码不能为空" },
          { pattern: /^1\d{10}$/, message: "手机号码不正确" },
        ],
        code: [
          { required: true, message: "验证码不能为空" },
          { pattern: /^\d{4,6}$/, message: "验证码为4-6位数字" },
        ],
      },
    };
  },
  methods: {
    async sendCode() {
      await this.$refs.loginForm.validate("mobile");
      console.log("验证通过");
      await sendSms(this.user.mobile);
      this.$toast.success("短信验证码发送成功");
      this.sending = true;
    },
    async login() {
      try {
        this.loading = true;
        const res = await login(this.user);
        this.$toast.success("登录成功");
        // 把token储存起来
        // localStorage.setItem("token", res.data.token);
        this.$store.commit('setUser', res.data)
        //跳转到个人中心页面
        this.$router.push('/my')
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style>
.login-btn {
  margin: 16px;
}
</style>